//
//  WmcJoinTeamVM.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/15.
//

import Foundation
import RxRelay

// MARK: - [WmcJoinTeamVM]

class WmcJoinTeamVM: WmcBaseVM {
    let teams: BehaviorRelay<[WmcMediaTeamInfoModel]> = .init(value: [])

    /// 根据ID 查询团队信息
    /// - Parameter teamOpenId: teamOpenId description
    /// - Returns: description
    func queryTeamInfo(teamOpenId: String) {
        WmcMediaTeamManagerAPI.fetchTeamInfo(teamOpenId: teamOpenId).subscribe { [weak self] team in
            guard let weakSelf = self else { return }
            if team.teamId == nil {
                weakSelf.teams.accept([])
            } else {
                team.teamOpenId = teamOpenId
                weakSelf.teams.accept([team])
            }
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }

    /// 搜索团队号加入
    /// - Parameter teamId: 团队ID
    /// - Returns: description
    func joinTeam(teamId: Int?, succeed: (() -> Void)?) {
        WmcMediaTeamManagerAPI.addMember(teamId: teamId, type: .teamIdSearch).subscribe { res in
            guard let succeed = succeed else {
                return
            }
            WmcNotificationManager.shared.post(type: .joinTeamSucceed, object: nil)
            /// 同步配置
            let config = WmcMediaAlbumConfigurationModel()
            config.albumType = 1
            config.isSync = true
            config.name = res.remark ?? ""
            config.albumId = res.teamId ?? 0
            config.busId = res.teamId ?? 0
            WmcPreferenceSettingsManager.addTeamSyncConfig(model: config)
            WmcHudManager.toast("已成功加入团队")
            succeed()
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
}

extension WmcJoinTeamVM {
    func findCurrentJoinedTeam(teamId: Int, succeed: ((_ teamAlbum: WmcMediaTeamAlbumModel) -> Void)?) {
        WmcMediaTeamAlbumAPI.fetchTeamAlbumList().subscribe { list in
            guard let succeed = succeed else { return }
            list.forEach { album in
                if teamId == album.teamId {
                    succeed(album)
                }
            }
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
}
